# coding=utf-8
import datetime

from django.contrib import auth
from django.db import transaction
from rest_framework.authtoken.models import Token
from rest_framework.decorators import APIView, api_view
from rest_framework.response import Response

from sms.models import AuthSMS
from utils.decorators import need_login, operation_log
from utils.response_content import *
from utils.shortcuts import http_400_response, http_200_response, http_401_response
from .models import User, WorkerUser, BossUser
from .response_content import *
from .seriailzers import UserLoginSer, UserDetailSer, UserUpdataSer


class LoginView(APIView):
    def post(self, request, **kwargs):
        """用户登陆"""
        data = request.data.copy()
        ser = UserLoginSer(data=data)
        if ser.is_valid():
            username = ser.data['username']
            password = ser.data['password']
            # 手机号和用户名相同
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                request.session.set_expiry(60 * 60)
                auth.login(request, user)
                token, ok = Token.objects.get_or_create(user=user)
                ret_dict = UserDetailSer(user).data
                ret_dict['token'] = token.key
                return Response(ret_dict)
            else:
                return http_401_response(USER_DOES_NOT_EXIST_OR_WRONG_PASSWORD)
        else:
            return http_400_response(ARGUMENT_ERRORS)


class LogoutView(APIView):
    @need_login
    def post(self, request, **kwargs):
        """"用户登出"""
        auth.logout(request)
        return http_200_response(LOGOUT_SUCCESS)


class ChangePassWord(APIView):
    def put(self, request, **kwargs):
        """修改密码"""
        phone_number = request.data.get('phone_number', '')
        password = request.data.get('password', '')
        auth_code = request.data.get('auth_code', '')
        auths = AuthSMS.objects.filter(auth_code=auth_code, phone_number=phone_number)
        if auths.count() == 0:
            return http_400_response(WRONG_AUTH_SMS)
        auth_time = datetime.datetime.now()
        generate_time = datetime.datetime.fromtimestamp(auths[0].send_time)
        if (auth_time - generate_time).seconds > 300:
            auths[0].content = 'expired'
            auths[0].save()
            return http_400_response(AUTH_SMS_EXPIRED)
        if auths[0].content == 'expired':
            return http_400_response(AUTH_SMS_EXPIRED)
        else:
            auths[0].content = 'expired'
            auths[0].save()
        try:
            user = User.objects.get(username=phone_number)
        except User.DoesNotExist:
            return http_400_response(USER_DOES_NOT_EXIST)
        user.set_password(password)
        user.save()
        return http_200_response(CHANGE_PASSWORD_SUCCEED)


class UserView(APIView):
    @need_login
    @operation_log('user detail')
    def get(self, request, **kwargs):
        """'获取用户自己详情"""
        user = request.user
        return Response(UserDetailSer(user).data)

    def post(self, request, **kwargs):
        """"注册"""
        phone_number = request.data.get("phone_number", "")
        password = request.data.get("password", phone_number)
        auth_code = request.data.get("auth_code", "")
        # 用户是否存在
        if User.objects.filter(phone_number=phone_number).exists():
            return http_400_response(PHONE_NUMBER_HAS_BEEN_AUTHED)
        # 验证码
        auths = AuthSMS.objects.filter(auth_code=auth_code,
                                       phone_number=phone_number)
        if auths.count() == 0:
            return http_400_response(WRONG_AUTH_SMS)
        auth_time = datetime.datetime.now()
        generate_time = datetime.datetime.fromtimestamp(auths[0].send_time)
        if (auth_time - generate_time).seconds > 300:
            auths[0].content = 'expired'
            auths[0].save()
            return http_400_response(AUTH_SMS_EXPIRED)
        if auths[0].content == 'expired':
            return http_400_response(AUTH_SMS_EXPIRED)
        else:
            auths[0].content = 'expired'
            auths[0].save()
        with transaction.atomic():  # 事务处理 出错回滚
            user = User.objects.create(username=phone_number, phone_number=phone_number,
                                       usertype="unselected")  # 默认未选择类型
            user.set_password(password)
            user.save()
        return http_200_response(REGISTER_SUCCESS)

    @need_login
    @operation_log('update user detail')
    def put(self, request, **kwargs):
        """"用户修改自己的可修改信息"""
        data = request.data.copy()
        try:
            ser = UserUpdataSer(request.user, data=data, partial=True)
            ser.update(request.user, data)
        except Exception as e:
            return http_400_response(e)
        return Response(UserDetailSer(request.user).data)


@api_view(['POST'])
def choose_type(request):
    user = request.user
    data = request.data.copy()
    _type = data.get('user_type', 'unselected')
    print(data, _type)
    if _type == 'worker':
        try:
            WorkerUser.objects.get(user=user)
        except WorkerUser.DoesNotExist:
            WorkerUser.objects.create(user=user).save()
        user.usertype = _type
        user.save()
        return http_200_response(USER_TYPE_CHANGED_SUCCESS)
    elif _type == 'boss':
        try:
            BossUser.objects.get(user=user)
        except WorkerUser.DoesNotExist:
            BossUser.objects.create(user=user).save()
        user.usertype = _type
        user.save()
        return http_200_response(USER_TYPE_CHANGED_SUCCESS)
    else:
        return http_400_response(ARGUMENT_ERRORS)
